#include "stdafx.h"
#include "Parser.h"
#include "Parser_Combinator.h"

Parser_Type::Parser_Type(TYPE _Type,BOOL _Not) : Type(_Type),Not(_Not),
	Parser_Combinator((Combinator_MemoryManager<CParser_Input,CParser_Output>*)&g_Parser_MemoryManager)
{
}

CParser_Output Parser_Type::Parser(CParser_Input& input)
{
	CParser_Output Result(input,GetMM());
	if(input.Index() == input.LexerTokenListPtr()->Size()) return Result;
	NAutoPtr<CLexer_Token> Token = (*input.LexerTokenListPtr())[input.Index()];
	if(!Not)
	{
		if(Token->Type() == Type)
		{
			input.Index()++;
			Result.Count() = 1;
			Result.SetResult(TRUE);
			switch(Token->Type())
			{
			case ttString:
				StringStack.Push(Token);
				input.StringCount()++;
				break;
			default:
				SymbolStack.Push(Token);
				input.SymbolCount()++;
				break;
			}
		}
	}
	else
	{
		if(Token->Type() != Type)
		{
			input.Index()++;
			Result.Count() = 1;
			Result.SetResult(TRUE);
			switch(Token->Type())
			{
			case ttString:
				StringStack.Push(Token);
				input.StringCount()++;
				break;
			default:
				SymbolStack.Push(Token);
				input.SymbolCount()++;
				break;
			}
		}
	}
	return Result;
}

Parser_Str::Parser_Str(LPTSTR _value,BOOL _Not) : value(_value),Not(_Not),
	Parser_Combinator((Combinator_MemoryManager<CParser_Input,CParser_Output>*)&g_Parser_MemoryManager)
{
}

CParser_Output Parser_Str::Parser(CParser_Input& input)
{
	CParser_Output Result(input,GetMM());
	if(input.Index() == input.LexerTokenListPtr()->Size()) return Result;
	NAutoPtr<CLexer_Token> Token = (*input.LexerTokenListPtr())[input.Index()];
	int Len = wcslen(value);
	if(!Not)
	{
		if(Token->Length() == Len)
		{
			for(int i=0;i<Len;i++)
			{
				if(Token->Content()[i] != value[i]) return Result;
			}
			input.Index()++;
			Result.Count() = 1;
			Result.SetResult(TRUE);
			SymbolStack.Push(Token);
			input.SymbolCount()++;
		}
	}
	else
	{
		if(Token->Length() != Len)
		{
			input.Index()++;
			Result.Count() = 1;
			Result.SetResult(TRUE);
			SymbolStack.Push(Token);
			input.SymbolCount()++;
		}
		else
		{
			BOOL bResult = FALSE;
			for(int i=0;i<Len;i++)
			{
				if(Token->Content()[i] != value[i])
				{
					bResult = TRUE;
					break;
				}
			}
			if(bResult)
			{
				input.Index()++;
				Result.Count() = 1;
				Result.SetResult(TRUE);
				SymbolStack.Push(Token);
				input.SymbolCount()++;
			}
		}
	}
	return Result;
}

Parser_Combinator_Node::Parser_Combinator_Node()
	: theFunction(0),Combinator_Node<CParser_Input,CParser_Output>((Combinator_MemoryManager<CParser_Input,CParser_Output>*)&g_Parser_MemoryManager)
{
}

CParser_Output Parser_Combinator_Node::Parser(CParser_Input& input)
{
	CParser_Output Result = __super::Parser(input);
	if(Result)
	{
		if(theFunction)
			if(!theFunction())
				Result.SetResult(FALSE);
	}
	return Result;
}